/*
 * @Description:登录 存储token与用户信息
 * @Autor: lcz
 * @LastEditors: lcz
 * @LastEditTime: 2023-10-12 14:23:57
 */
import type { Dispatch } from "redux";
import * as types from "../../action-types";
import { loginByPassword, userDetail } from "@/api/user";
import { CookieClass } from "@/utils/tools/auth";

export const setToken = (token: string) => {
  return {
    type: types.SET_TOKEN,
    token
  };
};

export const setUserInfo = (userInfo: any) => {
  return {
    type: types.SET_USERINFO,
    userInfo
  };
};

const env = import.meta.env;

export const login = (requestData: { [key: string]: any }) => (dispatch: Dispatch) => {
  return new Promise((resolve, reject) => {
    loginByPassword(requestData)
      .then(response => {
        let { token, refreshToken } = response.data;
        dispatch(setToken(token));
        // dispatch(setUserInfo(data));
        CookieClass.set(`${env.VITE_APP_PROJECT_NAME_PREFIX}_refreshToken`, refreshToken);
        CookieClass.set(`${env.VITE_APP_PROJECT_NAME_PREFIX}_token`, token);

        userDetail().then(res => {
          dispatch(setUserInfo(res.data));
          CookieClass.set(`${env.VITE_APP_PROJECT_NAME_PREFIX}_userInfo`, JSON.stringify(res.data));
          resolve({
            ...res,
            token,
            refreshToken
          });
        });
      })
      .catch(error => {
        reject(error);
      });
  });
};
